<script setup lang="ts">
import { ref, onBeforeUnmount, reactive, onMounted, watch } from 'vue'
import { useUserStore } from '../store/modules/user';
import { useRouter } from "vue-router";
import { message } from 'ant-design-vue';
import { sessionStorage } from '../utils/storage';
import { download_file2, GetuserInfo } from '../utils/ipcRequest';
import { userSiteArticleZipImage, userSiteArticleList, articleLists, articleRemove,articleWithdraw, pictureUploadproxy,userSiteArticleDetails,userSiteArticleSetRelease,user_editPrev,articlePublish } from '../api/article'
const formState = reactive({
  checked1: false
});
const formStateRef = ref();
const labelCol = { span: 14 };
const wrapperCol = { span: 10 };
const userStore = useUserStore()
const router = useRouter();
const is_stop = ref(false) // 是否停止
const timer:any = ref(null)
const timer2:any = ref(null)
const timer3:any = ref(null)
const siteList:any = ref([])
const inProgressData:any = ref({})
const articleList:any = ref([])
const idxs:any = ref(0) // 默认记录站点列表的下标
const isDownloadResume = ref(false)
const imgNum = ref(0) // 记录上传图片个数
const arrIdx:any = ref([]) // 用来存储遍历的id,不同去获取，相同账号直接跳过获取token
const selectData:any = ref([]) // 发布前统一需要的内容
const count:any = ref(0)
onMounted(() => {
  isDownloadResume.value = false
  //在负责渲染的vue文件created生命周期函数中接受消息，做相应处理
  window.electron.ipcRenderer.removeAllListeners('updateProgressing2');
  window.electron.ipcRenderer.on('updateProgressing2', (_, value) => {
    console.log(idxs.value,'idxs.value')
    if(siteList.value.length > 0 && idxs.value >= 0) {
      siteList.value[idxs.value].progressBar = value.flag == 1  ?  value.process : ''
      if(value.type == 'completed' && value.process == '100%' && !isDownloadResume.value) {
        isDownloadResume.value = true
        siteList.value[idxs.value].download_status = true
        siteList.value[idxs.value].download_status_reason = `已解压`
      }
    }
  });
})
//离开界面
onBeforeUnmount(() => {
    // 每次离开当前界面时，清除定时器
    console.log('33243onBeforeUnmount')
    clearTimeout(timer.value)
    timer.value = null
    clearTimeout(timer2.value)
    timer2.value = null
    is_stop.value = true
    emits('change-switch', {is_stop: true})
    clearTimeout(timer3.value)
    timer3.value = null
})
const emits = defineEmits(['change-switch','is-see-details','p-refresh-data','publish-is-loading'])
const props:any = defineProps({
    siteList: {
      type: Array,
      required: true,
    },
    isStop: {
      type: Boolean,
      required: true,
    },
    isDefaultCan: {
      type: Boolean,
      required: true,
    }
})
watch([() => props.siteList, () => props.isDefaultCan, () => props.isStop] , ([newValue1, newValue2, newValue3], [oldValue1, oldValue2, oldValue3]) => {
    console.log(newValue1,newValue2,oldValue1,oldValue2,oldValue3,newValue1.length)
    siteList.value = newValue1
    is_stop.value = newValue3
    if(siteList.value.length > 0 && newValue2 && !newValue3) {
        articleList.value = []
        onSiteList()
    }
})
// watch(() => props.isStop, (newValue,oldValue) => {
//     console.log(newValue,oldValue, newValue.length)
//     is_stop.value = newValue
//     if(!newValue) {
//         onSiteList()
//     }
// })
const onSiteList = () => {
  console.log('223232323')
    let monitor = userStore.monitor
    formState.checked1 = monitor
    if(monitor == true && siteList.value.length > 0) {
        onArticleList(idxs.value)
    } else {
    if (timer.value) {
        clearTimeout(timer.value)
        timer.value = null
    }
    if (timer2.value) {
        clearTimeout(timer2.value)
        timer2.value = null
    }
    if (timer3.value) {
        clearTimeout(timer3.value)
        timer3.value = null
    }
    }
}
const onChangeMonitor = (e) => {
  console.log(e)
  formState.checked1 = e
  userStore.changeMonitor(e)
  if(formState.checked1 == true && siteList.value.length > 0) {
      emits('change-switch', {is_stop: false})
      // onArticleList(0)
  } else {
    emits('change-switch', {is_stop: true})
    is_stop.value = true
    if (timer.value) {
      clearTimeout(timer.value)
      timer.value = null
    }
    if (timer2.value) {
      clearTimeout(timer2.value)
      timer2.value = null
    }
    if (timer3.value) {
      clearTimeout(timer3.value)
      timer3.value = null
    }
  }
}
// 获取文章列表
const onArticleList = (idx:any) => {
  const executeNext = (index) => {
      if(index >= siteList.value.length) {
        clearTimeout(timer.value)
        clearTimeout(timer2.value)
        timer2.value = null
        timer.value = null
        emits('is-see-details', {isSeeDetails:true})  // 判断是否可以点进列表
        idxs.value = 0
        emits('p-refresh-data');
        emits('publish-is-loading', {isLoading:false})
        return
      }
      emits('publish-is-loading', {isLoading:false})
      siteList.value[idx].download_status = false
      siteList.value[idx].download_status_reason = ''
      siteList.value[idx].progressBar = ''
      siteList.value[idx].errorColor2 = ''
      siteList.value[idx].upload_status = false
      siteList.value[idx].upload_status_reason = ''
      siteList.value[idx].upload_text = ''
      siteList.value[idx].errorColor1 = ''
      siteList.value[idx].imgNum = ''
      siteList.value[idx].list_status = false
      siteList.value[idx].list_status_text = ''
      siteList.value[idx].list_status_reason = ''
      siteList.value[idx].errorColor = ''
      siteList.value[idx].isPublish = false // 发布状态
      siteList.value[idx].publishReason = ''
      siteList.value[idx].publishText = ''
      siteList.value[idx].errorColor3 = ''
      imgNum.value = 0
      selectData.value = []
      const currentItem = siteList.value[index];
      userSiteArticleList({page: 1,limit: 15, siteId: currentItem.site_id}).then((response:any) => {
        const result = response.data.data
        result.data.forEach((item:any) => {
          item.isDownload = false
        })
        if(siteList.value.length> 0) {
          inProgressData.value = siteList.value[idx]
        }
        processItems(result.data, idx)
      }).catch(() => {
        timer.value = setTimeout(() => {
          executeNext(index + 1)
        }, 2000)
      })
    }
    executeNext(idx)
}

// 默认获取是否有下载
const processItems = async (data:any, idx:any) => {
      for (let i in data) {
        let path = `images_${data[i].article_id}`; // 从开始到点号位置截取字符串
        const result = await window.electron.ipcRenderer.invoke('list-directory', path); // 等待操作完成
        // console.log(result)
        // 处理结果或更新数组项
        if(Array.isArray(result.imageArr)) {
          if(result.imageArr.length != 0) {
            data[i]['isDownload'] = true
            data[i]['downloadReason'] = '已解压' // 将修改后的对象添加到新数组中
          } else {
            data[i]['isDownload'] = false
            data[i]['downloadReason'] = ''
          }
        } else {
          data[i]['isDownload'] = false
          data[i]['downloadReason'] = ''
        }

        // 获取图片文件
        let pathJson = `images_${data[i].article_id}.json`;
        const resFile = await window.electron.ipcRenderer.invoke('json-directory', pathJson); // 等待操作完成
        // console.log(resFile,'resFile')
        if(resFile.type == 2) {
          let jsonData = JSON.parse(resFile.urlArr)
          data[i]['isUpload'] = true
          data[i]['uploadReason'] = '已上传' // 将修改后的对象添加到新数组中
          data[i]['uploadText'] = '已上传'
          data[i]['imgNum'] = jsonData.data.length
        } else if(resFile.type == 1 && data[i]['is_release'] == 0 && data[i]['status'] == 50 && data[i]['img_status'] == 20 && data[i]['isDownload']) {
          data[i]['isUpload'] = false
          data[i]['uploadReason'] = '' // 将修改后的对象添加到新数组中
          data[i]['uploadText'] = ''
        } else {
          data[i]['isUpload'] = false
          data[i]['uploadReason'] = '' // 将修改后的对象添加到新数组中
          data[i]['uploadText'] = ''
        }
        data[i]['name'] = siteList.value[idx]['name']
        data[i]['site_id'] = siteList.value[idx]['site_id']
        data[i]['prev_status'] = siteList.value[idx]['prev_status']
        data[i]['prev_time'] = siteList.value[idx]['prev_time']
        data[i]['cookie'] = siteList.value[idx]['port_config'] && siteList.value[idx]['port_config']['cookie'] ? siteList.value[idx]['port_config']['cookie'] : ''
        data[i]['activity_list'] = siteList.value[idx]['activity_list']
        data[i]['square_mission_List'] = siteList.value[idx]['square_mission_List']
        data[i]['publish_num_left'] = siteList.value[idx]['publish_num_left']
      }
      articleList.value = data
      onArticleZipImage(idx)
};
function getFilenameFromURL(url) {
    // 找到最后一个 '/' 的位置
    const lastIndex = url.lastIndexOf('/');
    // 使用 substring 从最后一个 '/' 位置之后开始截取，直到字符串末尾
    const filename = url.substring(lastIndex + 1);
    // 返回文件名，但不包括后缀名
    // return filename.split('.').slice(0, -1).join('.');
    return filename;
}

const onArticleZipImage = async (idx:any) => {
  let articleLists = articleList.value.filter((item1:any) => item1.is_release == 0 && item1.status == 50 && item1.img_status == 20 && !item1.isDownload)
  // if(!isStop.value) {
  console.log(articleLists,'articleLists')
  articleLists = articleLists.filter((_, index:any) =>index < 5)
  const executeNexts = (index) => {
    if(index >= articleLists.length) {
      console.log(siteList.value[idx].list_status.value,'执行顺序')
        timer2.value = setTimeout(() => {
          onDeleteRefresh(idx)
        }, 2000)
        siteList.value[idx].download_status = true
        siteList.value[idx].download_status_reason = `已解压`
      return
    }
    const currentItem = articleLists[index];
    if(currentItem['cover'] || currentItem['vertical_cover']) {
      userSiteArticleZipImage({articleId: currentItem['article_id']}).then(async(response:any) => {
          const result = response.data
          let urlValue = {
            url: result.url,
            fileName: getFilenameFromURL(result.url),
            article_id: currentItem['article_id']
          }
          console.log(result,urlValue,'result')
          siteList.value[idx].download_status = false  // 下载状态
          siteList.value[idx].download_status_reason = `正在解压`
          siteList.value[idx].errorColor2 = ''
          siteList.value[idx].progressBar = ''
          siteList.value[idx].upload_status = false // 上传状态
          siteList.value[idx].upload_status_reason = ''
          siteList.value[idx].upload_text = ''
          siteList.value[idx].errorColor1 = ''
          siteList.value[idx].imgNum = ''
          siteList.value[idx].list_status = false // 百家号文章监测状态
          siteList.value[idx].list_status_text = ''
          siteList.value[idx].list_status_reason = ''
          siteList.value[idx].errorColor = ''
          siteList.value[idx].isPublish = false // 发布状态
          siteList.value[idx].publishReason = ''
          siteList.value[idx].publishText = ''
          siteList.value[idx].errorColor3 = ''
          imgNum.value = 0
          idxs.value = idx
          emits('is-see-details', {isSeeDetails:false}) // 判断是否可以点进列表
          // 监听主进程的回复
         let downloadObj:any = await download_file2(result.url,currentItem['article_id'])
         console.log('下载返回的数据',downloadObj)
         let downloadResult = JSON.parse(downloadObj)
         if(downloadResult.success) {
            isDownloadResume.value = true
            if(downloadResult.status == 2 || downloadResult.status == 1) {
              currentItem.isDownload = true
              currentItem.downloadReason = '已解压'
              siteList.value[idx].download_status = true
              siteList.value[idx].download_status_reason = `已解压`
              timer2.value = setTimeout(() => {
                onDeleteRefresh(idx)
              }, 2000)
            }else if(downloadResult.status == 3 || downloadResult.status == 4) {
              currentItem.isDownload = false
              currentItem.downloadReason = downloadResult.message
              siteList.value[idx].download_status = false
              siteList.value[idx].download_status_reason = downloadResult.message
              timer2.value =  setTimeout(() => {
                executeNexts(index)
              }, 3000)
            } else{
              timer2.value = setTimeout(() => {
                executeNexts(index + 1)
              }, 2000)
              currentItem.isDownload = false
              currentItem.downloadReason = '解压失败'
              let pathJson = `images_${currentItem['article_id']}.zip`;
              siteList.value[idx].download_status = false
              siteList.value[idx].download_status_reason = `解压失败`
              window.electron.ipcRenderer.invoke('delete-file', pathJson).then(res => {
                if(res.success) {
                  console.log('文件删除成功')
                } else {
                  console.log('删除文件失败',res.message)
                }
              })
            }
         } else {
            currentItem.isDownload = false
            currentItem.downloadReason = '解压失败'
            siteList.value[idx].download_status = false
            siteList.value[idx].download_status_reason = `解压失败`
            siteList.value[idx].errorColor2 = 'error'
            timer2.value = setTimeout(() => {
              executeNexts(index + 1)
            }, 2000)
         }
      }).catch(() => {
        currentItem.isDownload = false
        currentItem.downloadReason = '下载失败'
        siteList.value[idx].download_status = false
        siteList.value[idx].download_status_reason = `解压失败`
        siteList.value[idx].errorColor2 = 'error'
        timer2.value = setTimeout(() => {
            executeNexts(index + 1)
          }, 2000)
      })
    } else {
      currentItem.isDownload = false
      currentItem.downloadReason = '无解压文件'
      siteList.value[idx].download_status = false
      siteList.value[idx].download_status_reason = `无解压文件`
      siteList.value[idx].errorColor2 = 'error'
      timer2.value = setTimeout(() => {
        executeNexts(index + 1)
      }, 2000)
    }
  }
  executeNexts(0)
}

const onDeleteRefresh = (idx:any) => {
  clearTimeout(timer3.value)
  timer3.value = null
  if(!is_stop.value) {
    console.log(arrIdx.value)
    if(arrIdx.value.length == 0 || (arrIdx.value.length > 0 && arrIdx.value[0] != idx)) {
      arrIdx.value.push(idx)
      const executeNextDel = (index) => {
        if(index >= siteList.value.length) {
          console.log('sdsdsdsdsddsd',siteList.value.length)
          // if(siteList.value.length != 0) {
          //   onDeleteRefresh(0)
          // }
          return
        }
        const currentItem = siteList.value[index];
        if(currentItem.port_config.cookie) {
          if(!is_stop.value) {
            onGetuserinfo(currentItem.port_config.cookie,currentItem.site_id , idx) // 从获取登陆信息，并从返回的header中拿到token
          }
        }
      }
      executeNextDel(idx)
      console.log('不同账户获取token')
    } else {
      console.log('相同账号直接跳过获取token')
      listUploadFun(idx,0)
    }
  }
}

// 从返回的header中解析出token
const onGetuserinfo = async (cookie,site_id:any, idx:any) => {
    let userInfoObj:any = await GetuserInfo(cookie,site_id)
    console.log('设置返回：',userInfoObj)
    let userInfoResult = JSON.parse(userInfoObj)
    if(userInfoResult.success) {
      listUploadFun(idx,0)
    } else {
      if (!is_stop.value) {
        siteList.value[idx].upload_status = false
        siteList.value[idx].upload_status_reason = '获取token失败'
        siteList.value[idx].upload_text = '请求失败'
        siteList.value[idx].errorColor1 = 'error'
        setTimeout(() => {
            arrIdx.value = []
            onArticleList(idx + 1)
        }, 5000)
      }
    }
}
// 执行图片上传事件
const listUploadFun = (idx:any,uploadIdx:any) => {
  let articleList2 = articleList.value.filter((item1:any) =>item1.is_release == 0 && item1.status == 50 && item1.img_status == 20 && item1.isDownload && !item1.isUpload)
  // let articleList3 = articleList.value.filter((item1:any) =>item1.is_release == 1 || item1.isDownload)
  articleList.value.forEach(item1 => {
    if (item1.is_release == 0 && item1.status == 50 && item1.img_status == 20  && item1.isDownload && !item1.isUpload) {
      item1.isUpload = false
      item1.uploadText = ''
      item1.uploadReason = ''
    }
  });
  console.log(articleList2, 'articleList2')
  articleList2 = articleList2.filter((_, index:any) =>index < 5)
  if(!is_stop.value) {
    const executeNexts = async (index) => {
      if (index >= articleList2.length) {
        if (!is_stop.value) {
          siteList.value[idx].upload_status = true
          siteList.value[idx].upload_status_reason = '已上传'
          siteList.value[idx].upload_text = '已上传'
          let list = articleList.value.filter((item1:any) =>item1.is_release == 0 && item1.status == 50 && item1.img_status == 20 && item1.isDownload && item1.isUpload)
          siteList.value[idx].pulish_num = list.length
          onListDel(idx, false)
        }
        return
      }
      const currentItem = articleList2[index];
      const resArr = await window.electron.ipcRenderer.invoke('read-file', `images_${currentItem.article_id}`)
      console.log(resArr); // 输出下载成功信息
      if (Array.isArray(resArr)) {
        currentItem.isUpload = false
        currentItem.uploadReason = '正在上传'
        currentItem.uploadText = '正在上传'
        siteList.value[idx].upload_status = false
        siteList.value[idx].upload_status_reason = '正在上传'
        siteList.value[idx].upload_text = '正在上传'
        siteList.value[idx].errorColor1 = ''
        siteList.value[idx].imgNum = ''
        imgNum.value = 0
        uploadPhotos(resArr, currentItem.article_id, idx) // 上传图片
      }
    }
    executeNexts(uploadIdx)
  }
}
// 上传图片
const uploadPhotos = async (val:any, article_id:any, idx:any) => {
  // 同步请求
  var array:any = []
  const executeNexts = async (index) => {
    // 判断循环执行完了后执行
    if(index >= val.length) {
      let pathJson = `images_${article_id}.json`;
      let datas = { data: array}
      console.log(datas)
      const result = await window.electron.ipcRenderer.invoke('create-file', pathJson, datas);
      console.log(result,'文件创建成功!')
      if (result.success) {
        articleList.value.forEach(item1 => {
          if (article_id == item1.article_id && item1.is_release == 0) {
            item1.isUpload = true
            item1.uploadReason = '已上传'
            item1.uploadText = '已上传'
            item1.imgNum = imgNum.value
          }
        });
        siteList.value[idx].upload_status = true
        siteList.value[idx].upload_status_reason = '已上传'
        siteList.value[idx].upload_text = '已上传'
        siteList.value[idx].imgNum = imgNum.value
        setTimeout(() => {
          listUploadFun(idx, 0)
        }, 2000)
      } else {
        articleList.value.forEach(item1 => {
          if (article_id == item1.article_id && item1.is_release == 0) {
            item1.isUpload = false
            item1.upload_text = '上传失败'
            item1.uploadReason = '文件创建失败'
          }
        });
        siteList.value[idx].upload_status = false
        siteList.value[idx].upload_status_reason = '文件创建失败'
        siteList.value[idx].upload_text = '上传失败'
        siteList.value[idx].errorColor1 = 'error'
        console.log(`创建文件失败：${result.message}`);
        if (!is_stop.value) {
          onListDel(idx, false)
        }
      }
      console.log('sdsssdfsdf', array)
      return
    }
    if(!is_stop.value) {
      const currentItem = val[index];
      const blob = new Blob([currentItem.data],{type: "application/octet-stream"}); //, { type: `${item.type}`} 根据文件类型调整 MIME 类型
      // let file:any =  new File([currentItem.data],currentItem.name,{type:currentItem.type})
      const FormDatas = new FormData();
      FormDatas.append("type", 'image');
      FormDatas.append("app_id", '1788758126357619');
      FormDatas.append("is_waterlog", '0');
      FormDatas.append("save_material", '1');
      FormDatas.append("is_events", '');
      FormDatas.append("article_type", 'news');
      FormDatas.append("media", blob, currentItem.name);
      // array = new Promise((resolve, reject) => {
      //api.upload_uploadImages后端给的图片上传解析的接口方法
      pictureUploadproxy(FormDatas).then((response:any) => {
        const result = response.data.ret
        let width:any = ''
        let height:any = ''
        const img = new Image();
        img.src = result.https_url;
        img.onload = () => {
          // 图片加载完成后，获取宽高
          // console.log('Width:', img.width, 'Height:', img.height);
          // 可以在这里做一些处理，比如验证图片尺寸等
          width = img.width
          height = img.height
        };
        let articleId = { article_id: article_id, width: width, height: height }
        imgNum.value = index + 1
        siteList.value[idx].imgNum = index + 1
        let urlValue = {
          status: 'fulfilled',
          value:{...result, ...articleId }
        }
        array.push(urlValue)
        setTimeout(() => {
          executeNexts(index + 1)
        }, 1000)
        // resolve(urlValue)
      }).catch((err) => {
        // reject(err)
        articleList.value.forEach(item1 => {
          if (article_id == item1.article_id && item1.is_release == 0) {
            item1.isUpload = false
            item1.uploadReason = err.message
            item1.upload_text = '上传失败'
          }
        });
        siteList.value[idx].upload_status = false
        siteList.value[idx].upload_status_reason = err.message
        siteList.value[idx].upload_text = '上传失败'
        siteList.value[idx].errorColor1 = 'error'
        siteList.value[idx].imgNum = ''
        // console.log(err.message)
        if (!is_stop.value) {
          onListDel(idx, false)
        }
      })
    }
  }
  executeNexts(0)
}

// 百家号文章列表-定时监测数据
const onListDel = (idx:any, isNext:any) => {
  let obj = {
        currentPage: 1,
        pageSize: 10,
        search: '',
        type: 'news',
        collection: '',
        clearBeforeFetch: false
    }
    if(!is_stop.value) {
      siteList.value[idx].list_status = false
      siteList.value[idx].list_status_text = '正在监测标红'
      siteList.value[idx].list_status_reason = '正在监测标红'
      articleLists(obj).then((response:any) => {
        const result = response.data.data
        let arr = result.list.filter((item2:any) => item2['status'] == 'rejected' || (item2['status'] == 'publish' && item2.audit_msg != '') || (item2['status'] == 'forbidden' && item2.audit_msg != ''))
        // 自动删除审核未通过的文章
        if(arr.length > 0) {
            const executeNext2 = (index) => {
              if(index >= arr.length) {
                siteList.value[idx].list_status = true
                siteList.value[idx].list_status_text = '已完成'
                siteList.value[idx].list_status_reason = '已完成'
                console.log(idx)
                if(!is_stop.value) {
                  if(isNext) {
                    setTimeout(() => {
                        arrIdx.value = []
                        onArticleList(idx + 1)
                    }, 5000)
                  } else {
                    onDoedUpedList(0, idx)
                  }
                }
                return
              }
              siteList.value[idx].list_status = false
              siteList.value[idx].list_status_text = '正在删除标红'
              siteList.value[idx].list_status_reason = '正在删除标红'
              if(arr[index]['status'] == 'publish') {
                if(!is_stop.value) {
                  // 状态已发布-先撤回再删除
                  articleWithdraw({article_id: arr[index]['article_id']}).then((response:any) => {
                      const result = response.data
                      console.log('articleRemove',result)
                      articleRemove({article_id: arr[index]['article_id']}).then((response:any) => {
                          console.log(`异步操作: ${ arr[index]['article_id']}`, response);
                          timer3.value =  setTimeout(() => {
                            executeNext2(index+1)
                          }, 2000)
                          siteList.value[idx].list_status = true
                          siteList.value[idx].list_status_text = '已删除'
                          siteList.value[idx].list_status_reason = '已删除'
                      }).catch((err) => {
                        timer3.value =  setTimeout(() => {
                          executeNext2(index+1)
                        }, 2000)
                        siteList.value[idx].list_status = false
                        siteList.value[idx].list_status_reason = err.message
                        siteList.value[idx].list_status_text = '删除失败'
                        siteList.value[idx].errorColor = 'error'
                      });
                  }).catch((err) => {
                    timer3.value =  setTimeout(() => {
                      executeNext2(index+1)
                    }, 2000)
                    siteList.value[idx].list_status = false
                    siteList.value[idx].list_status_reason = err.message
                    siteList.value[idx].list_status_text = '删除失败'
                    siteList.value[idx].errorColor = 'error'
                  });
                }
              } else {
                if(!is_stop.value) {
                  articleRemove({article_id: arr[index]['article_id']}).then((response:any) => {
                      console.log(`异步操作: ${ arr[index]['article_id']}`, response);
                      timer3.value = setTimeout(() => {
                        executeNext2(index+1)
                      }, 2000)
                      siteList.value[idx].list_status = true
                      siteList.value[idx].list_status_text = '已删除'
                      siteList.value[idx].list_status_reason = '已删除'
                  }).catch((err) => {
                    timer3.value = setTimeout(() => {
                      executeNext2(index+1)
                    }, 3000)
                    siteList.value[idx].list_status = false
                    siteList.value[idx].list_status_reason = err.message
                    siteList.value[idx].list_status_text = '删除失败'
                    siteList.value[idx].errorColor = 'error'
                  });
                }
              }
            }
            executeNext2(0)
        } else {
          if(!is_stop.value) {
            if(isNext) {
              setTimeout(() => {
                  arrIdx.value = []
                  onArticleList(idx + 1)
              }, 5000)
            } else {
              onDoedUpedList(0, idx)
            }
          }
          siteList.value[idx].list_status = true
          siteList.value[idx].list_status_text = '已完成'
          siteList.value[idx].list_status_reason = '已完成'
        }
      }).catch((err) => {
        siteList.value[idx].list_status = false
        siteList.value[idx].list_status_reason = err.message
        siteList.value[idx].list_status_text = '监测失败'
        siteList.value[idx].errorColor = 'error'
        if(!is_stop.value) {
          if(isNext) {
            setTimeout(() => {
                arrIdx.value = []
                onArticleList(idx + 1)
            }, 5000)
          } else {
            onDoedUpedList(0,idx)
          }
        }
      })
    }
}
// 获取已下载和已上传的文章列表
const onDoedUpedList = (j:any, idx:any) => {
  let resultData:any = articleList.value.filter((item2:any) =>item2.is_release == 0 && item2.status == 50 && item2.img_status == 20 && item2.isDownload && item2.isUpload);
  console.log(resultData)
  const executeNext = async (index) => {
    if(index >= resultData.length) {
      if(!is_stop.value) {
        setTimeout(() => {
            arrIdx.value = []
            onArticleList(idx + 1)
        }, 5000)
      }
      return
    }
    if(!is_stop.value) {
      siteList.value[idx].isPublish = false
      siteList.value[idx].publishReason = '正在发布'
      siteList.value[idx].publishText = '正在发布'
      emits('publish-is-loading', {isLoading:true})  // 正在发布判断按钮进行加载状态
      const currentItem = resultData[index];
      console.log(currentItem,'下载上传列表',idx)
      // 判断今日剩余发布数是否大于0
      if(currentItem.publish_num_left > 0) {
        selectData.value.push({
            site_id: currentItem['site_id'],
            cookie: currentItem['cookie'],
            prev_status: currentItem['prev_status'],
            prev_time: currentItem['prev_time'],
            info: {},
            articleId: currentItem['article_id'],
            fileLists: [],
            modalOpen: false,
            vertical_cover: currentItem['vertical_cover'],
            activity_list: currentItem['activity_list'],
            square_mission_List: currentItem['square_mission_List']
        })
        const filePathJson = `images_${currentItem['article_id']}.json`;
        const result = await window.electron.ipcRenderer.invoke('json-directory', filePathJson);
        console.log(result)
        if (result.type == 2) {
            let jsonData =  JSON.parse(result.urlArr)
            console.log(jsonData)
            if(jsonData.data.length == 0) {
                window.electron.ipcRenderer.invoke('delete-file', filePathJson).then(res => {
                    console.log(res)
                    if(res.success) {
                      console.log('文件删除成功')
                    } else {
                      console.log('删除文件失败',res.message)
                    }
                })
                // message.warning('文件为空，请刷新重新上传');
                currentItem['isPublish'] = false
                currentItem['publishReason'] = '文件为空,请刷新'
                currentItem['errorColor3'] = 'error'
                currentItem['publishText'] = '发布失败'
                siteList.value[idx].isPublish = false
                siteList.value[idx].publishReason = '文件为空,请刷新'
                siteList.value[idx].publishText = '监测失败'
                siteList.value[idx].errorColor3 = 'error'
                emits('publish-is-loading', {isLoading:false})
                setTimeout(() => {
                  selectData.value = selectData.value.filter((items:any) => items.articleId !== currentItem.article_id);
                  executeNext(index+1)
                }, 3000)
            } else {
                selectData.value?.forEach((item: any, index:any) => {
                  if (currentItem['article_id'] === item.articleId) {
                    selectData.value[index]['fileLists'] = jsonData.data; // 替换为空的内容部分--给数组赋值
                    selectData.value[index]['modalOpen'] = true
                  }
                });
                onArticleDetails(currentItem['article_id'],idx, j) // 获取详情内容
            }
        }else if(result.type == 1) {
            currentItem['isPublish'] = false
            currentItem['publishReason'] = '未读取到文件'
            currentItem['errorColor3'] = 'error'
            currentItem['publishText'] = '发布失败'
            siteList.value[idx].isPublish = false
            siteList.value[idx].publishReason = '未读取到文件'
            siteList.value[idx].publishText = '发布失败'
            siteList.value[idx].errorColor3 = 'error'
            emits('publish-is-loading', {isLoading:false})
            setTimeout(() => {
              selectData.value = selectData.value.filter((items:any) => items.articleId !== currentItem.article_id);
              executeNext(index+1)
            }, 3000)
        } else {
            console.log(`读取文件失败：${result.message}`);
            currentItem['isPublish'] = false
            currentItem['publishReason'] = `读取${filePathJson}文件失败`
            currentItem['errorColor3'] = 'error'
            currentItem['publishText'] = '发布失败'
            siteList.value[idx].isPublish = false
            siteList.value[idx].publishReason = `读取${filePathJson}文件失败`
            siteList.value[idx].publishText = '发布失败'
            siteList.value[idx].errorColor3 = 'error'
            emits('publish-is-loading', {isLoading:false})
            setTimeout(() => {
              selectData.value = selectData.value.filter((items:any) => items.articleId !== currentItem.article_id);
              executeNext(index+1)
            }, 3000)
        }
      } else {
        siteList.value[idx].isPublish = false
        siteList.value[idx].publishReason = `今日剩余发布0,已达上限`
        siteList.value[idx].publishText = '发布上限'
        siteList.value[idx].errorColor3 = ''
        emits('publish-is-loading', {isLoading:false})
        if(!is_stop.value) {
          setTimeout(() => {
              arrIdx.value = []
              onArticleList(idx + 1)
          }, 5000)
        }
      }
    }
  }
  executeNext(j)
}
// 文章详情
const onArticleDetails = (articleId:any, idx:any, j) => {
  userSiteArticleDetails({articleId: articleId}).then((response:any) => {
      const result = response.data.data
      if(result) {
          selectData.value?.forEach((item: any, index:any) => {
              if (articleId === item.articleId) {
                  selectData.value[index]['info'] = result; // 替换为空的内容部分
                  count.value++
              }
          });
      } else {
          selectData.value = selectData.value.filter((item1:any) =>articleId != item1.articleId)
          if(selectData.value.length == 0) {
              message.warning('文章为空');
          }
      }
      console.log('selectData.value',count.value, selectData.value)
      if(!is_stop.value) {
        onConfirm(0, idx, j)
      }
  }).catch(err => {console.log(err)})
}
// 百家号发布文章
const onConfirm = (index:any, idx:any, j:any) => {
  console.log('选中：',selectData.value)
  if(selectData.value.length > 0 && !is_stop.value) {
    const currentItem = selectData.value[index];
    let html_content:any = '' // html内容
    const resultData = currentItem.fileLists?.reduce((acc:any, item1:any) => {
        let matchingItem:any = ''
        if(!Array.isArray(currentItem.info['images'])) {
            matchingItem = JSON.parse(currentItem.info['images']).find((item2:any) => item2.url.slice(item2.url.lastIndexOf('/') + 1) === item1.value.name);
        } else {
            matchingItem = currentItem.info['images'].find((item2:any) => item2.url.slice(item2.url.lastIndexOf('/') + 1) === item1.value.name);
        }
        if (matchingItem) {
            acc.push({  ...matchingItem,...item1.value }); // 将合并后的对象添加到结果数组中
        }
        return acc;
    }, []); // 初始值为空数组
    // html内容
    if(resultData.length > 0) {
        resultData.forEach((element:any, indexs:any) => {
        if(indexs == 0) {
            html_content = currentItem.info.html_content.replace(element.key, `<img src="${element.https_url}" alt="">`);
        } else {
            html_content = html_content.replace(element.key, `<img src="${element.https_url}" alt="">`);
        }
        });
    } else {
        html_content = currentItem.info.html_content
    }
    if(currentItem.info['min_title'] && !Array.isArray(currentItem.info['min_title']))  {
        JSON.parse(currentItem.info['min_title']).forEach((element:any) => {
            html_content = html_content.replace(element.label,element.html);
        });
    }else  {
        currentItem.info['min_title'].forEach((element:any) => {
            html_content = html_content.replace(element.label,element.html);
        })
    }
    let cover_image = currentItem.fileLists?.find((items:any) => currentItem.info.cover.slice(currentItem.info.cover.lastIndexOf('/') + 1) === items.value.name); // 封面图
    let cover_image2:any = {}
    if(!cover_image) {
        // 无封面图获取第一张图片
        cover_image2 = currentItem.fileLists?.find((_,indexs:any) => indexs == 0);
    }
    let vertical_cover_image = currentItem.fileLists?.find((items:any) => currentItem.vertical_cover.slice(currentItem.vertical_cover.lastIndexOf('/') + 1) === items.value.name); // 竖版封面图
    let url = `https://www.huaicaikeyu.cn${currentItem.info.cover}`
    let cover_images_map = JSON.stringify([
        {
            'src': cover_image ? cover_image.value.https_url : cover_image2.value.https_url,
            'origin_src': cover_image ? url : cover_image2.value.https_url
        }
    ])
    console.log(vertical_cover_image, '竖版封面图', currentItem.info.title.length,'标题长度')
    let activityLists:any = [
        {'id': 408, 'is_checked': 1},
        {'id': 'aigc_bjh_status', 'is_checked': 1} // AI创作声明
    ]
    if(currentItem.activity_list.length > 0) {
        let activity_list = currentItem.activity_list.filter((items:any) => items.id == 'ttv');
        if(activity_list.length> 0) {
            activityLists.push({'id': 'ttv', 'is_checked': 1})  // 自动生成视频
        } else {
            activityLists.push({'id': 'ttv', 'is_checked': 0})  // 自动生成视频
        }
    } else{
        activityLists.push({'id': 'ttv', 'is_checked': 0})  // 自动生成视频
    }
    if(currentItem.square_mission_List.length > 0) {
        let mission_List = currentItem.square_mission_List.some((items:any) => items.id == '1600102');
        if(mission_List) {
            activityLists.push({'id': 'task_1600102', 'is_checked': 1})  // 征文任务
        } else {
            activityLists.push({'id': `task_${currentItem.square_mission_List[0].id}`, 'is_checked': 1}) // 征文任务
        }
    }
    console.log('征文任务:', activityLists)
    let objData: any = {
      'type': 'news',
      'title': currentItem.info.title.length > 30 ? currentItem.info.ai_title : currentItem.info.title,
      'content': html_content,
      'creative_method': 'bjh_pc_text',
      'vertical_cover': vertical_cover_image ? vertical_cover_image.value.https_url : '',  // 垂直图片
      'abstract': '',  // 摘要
      'len': html_content.length,
      'activity_list': activityLists,
      'source_reprinted_allow': 0,
      'abstract_from': 1,
      'isBeautify': false,
      'usingImgFilter': false,
      'cover_layout': 'one',
      'cover_images': JSON.stringify([
          {
              'src': cover_image ? cover_image.value.https_url :  cover_image2.value.https_url,
              'cropData': {
                  'x': 0,
                  'y': 0,
                  'width': cover_image && cover_image.value && cover_image.value.width ? cover_image.value.width : 300,
                  'height': cover_image && cover_image.value && cover_image.value.width ? cover_image.value.height :  200
              },
              'machine_chooseimg': 0,
              'isLegal': 0
          }
      ]),
      '_cover_images_map': cover_images_map,
      'source': 'choose-remote',
      'cover_source': 'upload',
      'subtitle': '',
      'bjhtopic_id': '',
      'bjhtopic_info': '',
      'clue': '',
      'bjhmt': '',
      'order_id': '',
      'aigc_rebuild': '',
      'image_edit_point': JSON.stringify([
          {'img_type': "cover", 'img_num': {'template': 0, 'font': 0, 'filter': 0, 'paster': 0, 'cut': 0, 'any': 0}},
          {'img_type': "body", 'img_num': {'template': 0, 'font': 0, 'filter': 0, 'paster': 0, 'cut': 0, 'any': 0}}
      ])
    }
    console.log('objData', objData, html_content)
    articlePublish(objData).then((response:any) => {
        const result = response.data.ret
        console.log('result',result, currentItem.articleId)
        getUserEditPrev(index, idx, true)
    }).catch((err) => {
        console.log(err)
        // message.error(err.message);
        articleList.value.forEach(item1 => {
          if (currentItem.articleId == item1.article_id && item1.is_release == 0) {
            item1.isPublish = false
            item1.publishText = '发布失败'
            item1.publishReason = err.message
            item1.errorColor3 = 'error'
          }
        });
        siteList.value[idx].isPublish = false
        siteList.value[idx].publishReason = err.message
        siteList.value[idx].publishText = '发布失败'
        siteList.value[idx].errorColor3 = 'error'
        emits('publish-is-loading', {isLoading:false})
        if(err.message == '登录已过期，请重新登录') {
          sessionStorage.remove(`bjhToken_${siteList.value[idx].site_id}`);
        }
        setTimeout(() => {
            arrIdx.value = []
            onArticleList(idx + 1)
        }, 5000)
    });
    // if(!is_stop.value) {
    //     onListDel(idx, true)
    // }
  } else if(selectData.value.length == 0 && !is_stop.value){
    siteList.value[idx].isPublish = false
    siteList.value[idx].publishReason = '获取文章内容为空'
    siteList.value[idx].publishText = '未发布'
    siteList.value[idx].errorColor3 = 'error'
    setTimeout(() => {
      selectData.value = []
      onDoedUpedList(j+1,idx)
    }, 3000)
  }
}
//获取当前时间
const formateDate = () => {
  const time = new Date()
  const year = time.getFullYear()
  const month = complement(time.getMonth() + 1)
  const day = complement(time.getDate())
  const hour = complement(time.getHours())
  const minute = complement(time.getMinutes())
  const second = complement(time.getSeconds())
  return `${year}-${month}-${day} ${hour}:${minute}:${second}`
}
//当时间为个位数的时候，在数字前加0
const complement = (value: number): string => {
  return value < 10 ? `0${value}` : value.toString()
}
// 判断是否可以发布
const getUserEditPrev = (index:any,idx:any, isAfter:any) => {
  const currentItem = selectData.value[index];
  let obj:any = {}
  if(isAfter) {
      obj = {
          prev_time: formateDate(),
          site_id: currentItem['site_id']
      }
  } else {
      obj = {
          site_id: currentItem['site_id'],
          prev_time: currentItem['prev_time'],
          prev_status: currentItem['prev_status']
      }
  }
  user_editPrev(obj).then((response:any) => {
      console.log('是否可以发布',response)
      siteList.value[idx]['prev_time'] = obj['prev_time']
      onArticleSetRelease(currentItem.articleId, idx)
  }).catch(() => {
      
  })
}

// 设置文章已发布
const onArticleSetRelease = async (articleId:any, idx:any) => {
  await userSiteArticleSetRelease({articleId: articleId}).then((response:any) => {
      message.success(response.message);
      articleList.value.forEach(item1 => {
        if (articleId == item1.article_id && item1.is_release == 0) {
          item1.isPublish = true
          item1.publishText = '发布成功'
          item1.publishReason = ''
        }
      });
      siteList.value[idx].isPublish = true
      siteList.value[idx].publishReason = `发布成功`
      siteList.value[idx].publishText = '发布成功'
      siteList.value[idx].errorColor3 = ''
      // handleOk(index + 1)
      // 发布后删除本地缓存文件
      let pathJson = `images_${articleId}`;
      window.electron.ipcRenderer.invoke('delete-file', pathJson+'.zip').then(res => {
        console.log(res)
        if(res.success) {
            console.log('文件删除成功zip')
        } else {
            console.log('删除文件失败',res.message)
        }
      })
      window.electron.ipcRenderer.invoke('delete-file', pathJson+'.json').then(res => {
        console.log(res)
        if(res.success) {
            console.log('文件删除成功json')
        } else {
            console.log('删除文件失败',res.message)
        }
      })
      window.electron.ipcRenderer.invoke('delete-folder', pathJson).then(res => {
        console.log(res)
        if(res.success) {
            console.log('文件夹删除成功')
        } else {
            console.log('删除文件夹失败',res.message)
        }
      })
      if(!is_stop.value) {
        onListDel(idx, true)
      }
  }).catch(err => {
      emits('publish-is-loading', {isLoading:false})
      console.log(err)
  })
}

// 退出登录
const onLogout = () => {
  userStore.removeLogout().then(() => {

  })
  sessionStorage.remove(`site_list_num`)
  is_stop.value = true
  emits('change-switch', {is_stop: true})
  router.push('/login')
}
</script>

<template>
    <div class="fullAutomaticPulish">
        <div class="home-top">
            <a-breadcrumb>
                <a-breadcrumb-item>首页</a-breadcrumb-item>
            </a-breadcrumb>
            <div style="display: flex;align-items: center;">
                <a-form
                style="margin-top: 0px"
                ref="formStateRef"
                layout="inline"
                :model="formState"
                :label-col="labelCol"
                :wrapper-col="wrapperCol"
                >
                    <a-form-item label="实时监测" name="region">
                        <a-switch v-model:checked="formState.checked1" checked-children="开" un-checked-children="关" @change="onChangeMonitor" />
                    </a-form-item>
                </a-form>
                <a class="logout" @click="onLogout" style="color:black">退出</a>
            </div>
        </div>
        <div v-if="inProgressData">
            <a-alert message="" type="info" banner :show-icon="false" closable>
                <template #description>
                    <p style="margin-bottom: 0;">
                        {{ inProgressData.name }}
                        <a-tag style="margin-left:20px" v-if="inProgressData.download_status" color="success">{{inProgressData.download_status_reason}}</a-tag>
                        <a-tag v-else-if="!inProgressData.download_status && inProgressData.download_status_reason" :color="inProgressData.errorColor2 ? inProgressData.errorColor2 : 'orange'">{{inProgressData.download_status_reason}} {{  inProgressData.progressBar && inProgressData.download_status_reason == '正在解压' ? (inProgressData.progressBar) : '' }}</a-tag>
                        <a-tag v-if="inProgressData.upload_status" color="blue">{{inProgressData.upload_text}}</a-tag>
                        <span v-else-if="!inProgressData.upload_status && inProgressData.upload_status_reason">
                            <a-tooltip>
                            <template #title>
                                <span>{{inProgressData.upload_status_reason}}</span>
                            </template>
                            <a-tag style="cursor: pointer;" :color="inProgressData.errorColor1 ? inProgressData.errorColor1 : 'gold'">{{inProgressData.upload_text}}</a-tag>
                            </a-tooltip>
                        </span>
                        <!-- 列表监测状态 -->
                        <a-tag v-if="inProgressData.list_status" color="default">{{inProgressData.list_status_text}}</a-tag>
                        <span v-else-if="!inProgressData.list_status && inProgressData.list_status_reason">
                            <a-tooltip>
                            <template #title>
                                <span>{{inProgressData.list_status_reason}}</span>
                            </template>
                            <a-tag style="cursor: pointer;" :color="inProgressData.errorColor ? inProgressData.errorColor : 'magenta'">{{inProgressData.list_status_text}}</a-tag>
                            </a-tooltip>
                        </span>
                        <!-- 发布状态 -->
                        <a-tag v-if="inProgressData.isPublish" color="geekblue">{{inProgressData.publishText}}</a-tag>
                        <span v-else-if="!inProgressData.isPublish && inProgressData.publishReason">
                            <a-tooltip>
                            <template #title>
                                <span>{{inProgressData.publishReason}}</span>
                            </template>
                            <a-tag style="cursor: pointer;" :color="inProgressData.errorColor3 ? inProgressData.errorColor3 : 'geekblue'">{{inProgressData.publishText}}</a-tag>
                            </a-tooltip>
                        </span>
                    </p>
                </template>
            </a-alert>
        </div>
    </div>
</template>
<style scoped>
.home-top{
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}
.logout{
  font-size: 14px;
  cursor: pointer;
}
</style>